<?php
include('class_mysql.php');
$db = new MySQLClass();
$db->connect(array('hostname'=>'127.0.0.1','username'=>'root','password'=>'yanjj','database'=>'ci-test'));
$data = requestFilter();
$f = isset($data['get']['f']) ? $data['get']['f'] : '' ;
$postData = isset($data['post']) ? $data['post'] : '' ;
if( ! empty($f) && function_exists($f))
{
    switch($f)
    {
        //添加用户
        case 'addUser':
            addUser($postData);
            break;
        //用户列表
        case 'listUser':
            listUser();
            break;
        //用户组列表
        case 'listUserGroup':
            listUserGroup();
            break;
        //添加用户组
        case 'addUserGroup':
            addUserGroup($postData);
            break;
        //用户组权限
        case 'getAuth':
            getAuth($postData);
            break;
        //设置用户组权限
        case 'setAuth':
            setAuth($postData);
            break;
        //查看节点
        case 'listNode':
            listNode();
            break;
        //添加节点
        case 'addNode':
            addNode($postData);
            break;
        default:
            break;
    }
}

//查看节点
function listNode($flag = TRUE)
{
    global $db;
    $sql = "select * from node order by id;";
    $data = $db->fetch_array($sql);
    if( ! $flag)
    {
        return $data;
    }
    echo json_encode($data);
    exit;
}

//添加节点
function addNode($data = array())
{
    global $db;
    $row = array();
    $rs = array('msg'=>'添加成功','status'=>'1');
    $row['model'] = $data['model'];
    $row['action'] = $data['action'];
    $pid = intval($data['pid']);
    $row['pid'] = intval($data['pid']);
    $sql = "select level,id,pid from node where id = {$pid}";
    $data = $db->fetch_once($sql);
    if(empty($data))
    {
        $rs['msg'] = '节点不存在。';
        $rs['status'] = 0;
        echo json_encode($rs);
        exit;
    }
    if($data['level'] == 1)
    {
        $row['level'] = 2;
    }
    else if($data['level'] == 2)
    {
        $row['level'] = 3;
    }
    else
    {
        $rs['msg'] = '节点level非法。';
        $rs['status'] = 0;
        echo json_encode($rs);
        exit;
    }
    if($data['pid'] == 0)
    {
        $row['pid'] = 1;
    }
    else if($data['pid'] == 1)
    {
        $row['pid'] = 2;
    }
    else
    {
        $rs['msg'] = '节点pid非法。';
        $rs['status'] = 0;
        echo json_encode($rs);
        exit;
    }
    $row['menu'] = $data['id'];
    $id = $db->insert('node',$row);
    if(empty($id))
    {
        $rs['msg'] = '添加失败';
        $rs['status'] = 0;
        echo json_encode($rs);
        exit;
    }
    echo json_encode($rs);
    exit;
}

//得到用户组权限
function getAuth($data = array())
{
    global $db;
    $id = isset($data['id']) ? intval($data['id']) : 0 ;
    $sql = "select id,action,pid,level from node";
    $data = $db->fetch_array($sql);
    $sql = "select node_id,role_id from access where role_id = {$id}";
    $ndata = $db->fetch_array($sql);
    $arr = array();
    if ( ! empty($ndata))
    {
        foreach ($ndata as $val)
        {
            $arr[$val['node_id']] = $val['role_id'];
        }
    }
    foreach ($data as $key=>$val)
    {
        $data[$key]['checked'] = empty($arr[$val['id']]) ? '' : 'checked="checked"' ;
    }
    $rs = get_trees($data,0,'pid','id');
    echo json_encode($rs);exit;
}

//设置用户组权限
function setAuth($data = array())
{
    global $db;
    $rs = array('msg'=>'设置成功','status'=>'1');
    $id = isset($data['id']) ? intval($data['id']) : 0 ;
    $nid = isset($data['nid']) ? $data['nid'] : 0 ;
    
    //判断是否存在该用户组
    $sql = "select id from role where id = {$id}";
    $data = $ndata = $db->fetch_once($sql);
    if(empty($data))
    {
        $rs['msg'] = '用户组不存在。';
        $rs['status'] = 0;
        echo json_encode($rs);
        exit;
    }
    $sql = "select id as node_id,level,pid from node where id in ({$nid})";
    $ndata = $db->fetch_array($sql);
    if(empty($ndata))
    {
        $rs['msg'] = '节点不存在。';
        $rs['status'] = 0;
        echo json_encode($rs);
        exit;
    }
    
    //先删除access权限下有关是$id的组数据
    $sql = "delete from access where role_id = {$id}";
    $db->query($sql);
    
    //然后再重新赋值
    foreach($ndata as $val)
    {
        $val['role_id'] = $id;
        $db->insert('access',$val);
    }
    echo json_encode($rs);
    exit;
}

//用户组列表
function listUserGroup()
{
    global $db;
    $sql = "select id,name,case status when 0 then '未激活' when 1 then '已激活' end as status from role";
    $data = $db->fetch_array($sql);
    echo json_encode($data);
    exit;
}

//用户列表
function listUser($flag = TRUE)
{
    global $db;
    $sql = "select user.id,user.username,role.name,role.pid,role.id as rid from user left join role_user on role_user.user_id = user.id left join role on role.id = role_user.role_id";
    $data = $db->fetch_array($sql);
    if( ! $flag)
    {
        return $data;
    }
    echo json_encode($data);
    exit;
}

//添加用户组
function addUserGroup($data = array())
{
    global $db;
    $rs = array('msg'=>'添加成功','status'=>'1');
    $row = $arr = array();
    if(empty($data['name']) OR empty($data['status']) OR empty($data['pid']) OR empty($data['remark']))
    {
        $rs['msg'] = '信息不完整，请填写。';
        $rs['status'] = 0;
        echo json_encode($rs);
        exit;
    }
    $row['status'] = intval($data['status']);
    if( ! in_array($row['status'],array('0','1')))
    {
        $rs['msg'] = '状态不正确';
        $rs['status'] = 0;
        echo json_encode($rs);
        exit;
    }
    $gdata = listUser(FALSE);
    foreach($gdata as $val)
    {
        $arr[$val['pid']] = $val['name'];
    }
    $row['pid'] = intval($data['pid']);
    if( ! isset($arr[$row['pid']]))
    {
        $rs['msg'] = '用户组不正确';
        $rs['status'] = 0;
        echo json_encode($rs);
        exit;
    }
    $row['remark'] = $data['remark'];
    $row['name'] = $data['name'];
    
    //添加用户
    $id = $db->insert('role',$row);
    if(empty($id))
    {
        $rs['msg'] = '添加失败';
        $rs['status'] = 0;
        echo json_encode($rs);
        exit;
    }
    echo json_encode($rs);
    exit;
}

//添加用户
function addUser($data = array())
{
    global $db;
    $rs = array('msg'=>'添加成功','status'=>'1');
    $arr = array();
    
    //进行用户名和密码判断
    if( ! isset($data['username']) OR empty($data['username']) OR ! preg_match('/^[0-9a-zA-Z]/i',$data['username']))
    {
        $rs['msg'] = '用户名不能为空，并且用户名为数字和字母组成';
        $rs['status'] = 0;
        echo json_encode($rs);
        exit;
    }
    if( ! isset($data['password']) OR empty($data['password']) OR ! preg_match('/^[0-9a-zA-Z]/i',$data['password']))
    {
        $rs['msg'] = '密码不能为空，并且密码为数字和字母组成';
        $rs['status'] = 0;
        echo json_encode($rs);
        exit;
    }
    
    //查询是否有相同的用户
    $sql = "select id from user where username = '{$data['username']}'";
    $rows = $db->fetch_once($sql);
    if( ! empty($rows))
    {
        $rs['msg'] = '已经存在该用户了';
        $rs['status'] = 0;
        echo json_encode($rs);
        exit;
    }
    
    $gdata = listUser(FALSE);
    foreach($gdata as $val)
    {
        $arr[$val['pid']] = $val['name'];
    }
    $row['pid'] = intval($data['pid']);
    if( ! isset($arr[$row['pid']]))
    {
        $rs['msg'] = '所属组不正确';
        $rs['status'] = 0;
        echo json_encode($rs);
        exit;
    }
    
    
    //添加用户
    $id = $db->insert('user',array('username'=>$data['username'],'password'=>md5($data['password'])));
    if(empty($id))
    {
        $rs['msg'] = '添加用户失败';
        $rs['status'] = 0;
        echo json_encode($rs);
        exit;
    }
    
    //添加中间表 role_user
    $db->insert('role_user',array('role_id'=>$data['pid'],'user_id'=>$id));
    
    echo json_encode($rs);
    exit;
}

/*------------ 处理用户提交过来的数据 --------------*/
function requestFilter($qtype = '') {
    $array = array(); $req = array('get' , 'post');
    if(!in_array($qtype , $req)) {
        foreach($req as $val) $array[$val] = requestFilter($val);
    } else {
        $req = $qtype == 'get' ? $_GET : $_POST;
        $qtype;
        $array = requestFilterArray($req);
    }
    return $array;
}
function requestFilterArray($request = array()) {
    $array = array();
    if(count($request) > 0) {
        foreach($request as $key => $value) {
            if(is_array($value)) {
                $array[$key] = requestFilterArray($value);
            } else {
                $array[$key] = preg_replace('/(\"|\')([^>]*>)|<[^>]*>[^<]*<[^>]*>|;[^;]*;(\"|\')/' , '' , urldecode(addslashes($value)));
            }
        }
    }
    return $array;
}
/*------------ 处理用户提交过来的数据 --------------*/

/*------------ 无限递归 --------------*/
function get_trees($arr = array(),$pId,$pField,$cField,$type=0)
{
    $tree = '';
    foreach ($arr as $k =>$v)
    {
        if($v[$pField] == $pId)
        {   
            if(empty($type))
            {
                $v[$pField] = get_trees($arr,$v[$cField],$pField,$cField);
                $tree[] = $v;
            }
            else
            {
                $tree[$pId] = get_parent($arr,$v[$cField],$pField,$cField);
            }
        }
    }
    return $tree;
}

function get_parent($arr = array(),$pId,$pField,$cField)
{
    $tree = '';
    foreach ($arr as $k => $v)
    {
        if($v[$pField] == $pId)
        {
            $tree[$pId] = get_parent($v[$cField],$pField,$cField);
        }
    }
    return $tree;
} 
/*------------ 无限递归 --------------*/
?>